package com.gin.kotlin.gf2gamecommunity.base.util

import android.content.Context
import coil3.ImageLoader
import coil3.SingletonImageLoader
import coil3.annotation.ExperimentalCoilApi
import coil3.decode.BlackholeDecoder
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.CachePolicy
import coil3.request.ImageRequest
import coil3.util.DebugLogger
import com.gin.kotlin.gf2gamecommunity.base.LogInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File

/**
 * 修改Coil默认的 OkHttpClient
 * @receiver Context
 * @param handle (OkHttpClient.Builder) -> OkHttpClient.Builder
 */
fun Context.setCoilDefaultClient(handle: (OkHttpClient.Builder) -> OkHttpClient.Builder = { it }) {
    SingletonImageLoader.setSafe {
        ImageLoader.Builder(this)
//            .logger(DebugLogger())
            .components {
                add(
                    OkHttpNetworkFetcherFactory(
                        callFactory = {
                            val builder = OkHttpClient().newBuilder()
                                .addInterceptor(LogInterceptor())
                                .cache(Cache(File(cacheDir, "image_cache"), 400.mb))
                            handle(builder)
                            builder.build()
                        }
                    )
                )
            }
            .build()
    }
}

/**
 * 预载网络图片
 * @receiver ImageLoader
 * @param url String
 * @param context Context
 * @return ImageResult
 */
@OptIn(ExperimentalCoilApi::class)
suspend fun ImageLoader.preload(url: String, context: Context) = this.execute(ImageRequest.Builder(context)
    .memoryCachePolicy(CachePolicy.DISABLED)
    .decoderFactory(BlackholeDecoder.Factory())
    .data(url).build())